//
//  JCUpdateViewController.m
//  Victor
//
//  Created by Guo.JC on 17/6/23.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "JCUpdateViewController.h"
#import "JCCircleProgressUpdate.h"
#import "YFAlertHelper.h"
#import "YFSportAndSensorApi.h"
#import "YFSensorManager.h"
@import iOSDFULibrary;

@interface JCUpdateViewController ()<LoggerDelegate, DFUProgressDelegate, DFUServiceDelegate>

@property (weak, nonatomic) IBOutlet UIView *progress;
@property (strong, nonatomic) JCCircleProgressUpdate *progressView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *exitBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *progressViewTop;
@property (assign , nonatomic) BOOL isUpdate;

@end

@implementation JCUpdateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)setup{
    _tipLabel.text = @"Please make sure that your device is over 20% battery power and keep the distance between the phone and the device to ensure smooth Bluetooth signal";
    _startBtn.layer.cornerRadius = 3;
    _startBtn.layer.masksToBounds = YES;
    self.title = @"Firmware Update";
    [_progress layoutIfNeeded];
    _progressView = [[JCCircleProgressUpdate alloc] initWithFrame:_progress.bounds];
    [_progress addSubview:_progressView];
    _progressView.trackColor = [[UIColor whiteColor] colorWithAlphaComponent:.3];
    _progressView.progressColor = [UIColor yellowColor];
}

///退出固件升级
- (IBAction)quitUpdateAction:(UIButton *)sender {
    if (_isUpdate) {
        [self.hud showString:@"UPGRADE..." dimissAfterSecond:2];
    }else{
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

///开始固件升级
- (IBAction)startUpdateAction:(UIButton *)sender {
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    sender.hidden = YES;
    _titleLabel.text = NSLocalizedString(@"Downloading the hardware file", @"正在下载固件包");
    _isUpdate = YES;
    __weak __typeof(self)weakSelf = self;
    [self downLoadFirmwarePakegeCompletion:^(NSString *packegePath, NSError *downError) {
        if (downError) {
            weakSelf.titleLabel.text = NSLocalizedString(@"Download failed", @"下载失败");
        }else{
            weakSelf.titleLabel.text = NSLocalizedString(@"Download successfully", @"下载成功");
            [weakSelf sendUpdateCommandCompletion:^(NSError *commandError) {
                if (commandError) {
                    
                }else{
                    [weakSelf DFUUpateWithPackegePath:packegePath];
                }
            }];
        }
    }];
}

///DFU升级
- (void)DFUUpateWithPackegePath:(NSString *)path{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        DFUFirmware *selectedFirmware = [[DFUFirmware alloc] initWithUrlToZipFile:[NSURL fileURLWithPath:path]];
        DFUServiceInitiator *initiator = [[DFUServiceInitiator alloc] initWithCentralManager:_manager
                                                                                      target:_peripheral];
        [initiator withFirmware:selectedFirmware];
        // Optional:
        // initiator.forceDfu = YES/NO; // default NO
        // initiator.packetReceiptNotificationParameter = N; // default is 12
        initiator.logger = self; // - to get log info
        initiator.delegate = self; // - to be informed about current state and errors
        initiator.progressDelegate = self; // - to show progress bar
        initiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = YES;
        // initiator.peripheralSelector = ... // the default selector is used
        DFUServiceController *controller = [initiator start];
        
    });
}

///发送固件升级指令
- (void)sendUpdateCommandCompletion:(void (^)(NSError *commandError)) completion{
    [YFCommunicationManager shareInstance].shouldRetryConnect = NO;//关闭自动重连
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeUpdateDevice parmaObject:@([YFCommunicationManager shareInstance].lgPeripheral.oemType) completionBlock:^(BOOL success, id response, NSError *error) {
        if (success) {
            completion(nil);
        }else{
            completion(error);
        }
    }];
}

///下载固件包
- (void)downLoadFirmwarePakegeCompletion:(void (^)(NSString *packegePath, NSError *downError)) completion{
    
    __weak typeof(self)weakSelf = self;
    [YFSportAndSensorApi downLoadFirware:[NSURL URLWithString:_firmwarePath] downLoadProress:^(float progress) {
        [weakSelf.progressView setProgress:progress animated:YES];
    } completion:^(NSString *path, NSError *error) {
        if (error) {
            completion(nil, error);
        }else{
            [weakSelf.progressView setProgress:1 animated:YES];
            completion(path, nil);
            YFLog(@"固件包路径 =  %@ ",path);
        }
    }];
}

#pragma mark - DFU代理
- (void)logWith:(enum LogLevel)level message:(NSString *)message{
    
    NSString *levelString;
    switch (level) {
        case LogLevelDebug:
        {
            levelString = @"Debug";
        }
            break;
        case LogLevelVerbose:
        {
            levelString = @"LogLevelVerbose";
        }
            break;
        case LogLevelInfo:
        {
            levelString = @"LogLevelInfo";
        }
            break;
        case LogLevelApplication:
        {
            levelString = @"LogLevelApplication";
        }
            break;
        case LogLevelWarning:
        {
            levelString = @"LogLevelWarning";
        }
            break;
        case LogLevelError:
        {
            levelString = @"LogLevelError";
        }
            break;
            
        default:
            break;
    }
    
    YFLog(@"\n ---> %@  : %@",levelString, message);
}

- (void)dfuStateDidChangeTo:(enum DFUState)state{
    
    switch (state) {
        case DFUStateConnecting:
        {
            _titleLabel.text = @"Device Connecting";
        }
            break;
        case DFUStateStarting:
        {
            _titleLabel.text = @"Device Start Upgrade";
        }
            break;
        case DFUStateEnablingDfuMode:
        {
            _isUpdate = NO;
            _titleLabel.text = @"Undo The Upgrade";
        }
            break;
        case DFUStateUploading:
        {
            _titleLabel.text = @"Upgrading";
        }
            break;
        case DFUStateValidating:
        {
            _isUpdate = NO;
            _titleLabel.text = @"Device Invalid Firmware";
        }
            break;
        case DFUStateDisconnecting:
        {
            _titleLabel.text = @"Disconnected";
        }
            break;
        case DFUStateCompleted:
        {
            _isUpdate = NO;
            _titleLabel.text = @"Upgrade Successfully";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.upgradeSuccess();
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        }
            break;
        case DFUStateAborted:
        {
            _isUpdate = NO;
            _titleLabel.text = @"Stop Upgrading";
        }
            break;
            
        default:
            break;
    }
}

- (void)dfuError:(enum DFUError)error didOccurWithMessage:(NSString *)message{
    YFLog(@"\n错误：%@",message);
    __weak typeof(self) weakSelf = self;
    [YFAlertHelper showAlertController:self Title:@"Prompt" message:@"Upgrade Faild" cancelTitle:nil defalutTitle:@"OK" cancelAction:nil defalutAction:^(UIAlertAction *action) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.upgradeSuccess();
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

- (void)dfuProgressDidChangeFor:(NSInteger)part outOf:(NSInteger)totalParts to:(NSInteger)progress currentSpeedBytesPerSecond:(double)currentSpeedBytesPerSecond avgSpeedBytesPerSecond:(double)avgSpeedBytesPerSecond{
    YFLog(@"升级状态 -->>> %ld%% (part%ld/%ld). speed:%f bps, avgSpeed:%f bps\n",(long)progress,(long)part, (long)totalParts, currentSpeedBytesPerSecond, avgSpeedBytesPerSecond);
    [_progressView setProgress:progress/100.0 animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
